package com.ihealthway.all.interfaces.dwihealth.service;

import com.ihealthway.all.interfaces.dwihealth.XMLBuilder;
import com.ihealthway.all.interfaces.dwihealth.vo.*;
import org.nutz.dao.impl.NutDao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import java.util.ArrayList;
import java.util.List;

/**
 * ServicePlan 业务逻辑
 * @author 凡梦星尘(elkan1788@gmail.com)
 */
@IocBean
public class DWServicePlanService {

    private static final Log logger = Logs.get();

    private String respCnt = XMLBuilder.simpleResp("1", "Success", null);


    @Inject
    private NutDao dao;

    public String syncAdd(List<DWServicePlan> servicePlans) {
        String respContent = this.respCnt;

        List<ErrorInfoElement> errors = new ArrayList<>();
        List<DWServicePlan> data = new ArrayList<>();
        List<DWSerPlanItem> subData = new ArrayList<>();

        for (DWServicePlan serPlan : servicePlans) {
            ErrorInfoElement error = serPlan.valid();
            if (error!=null) {
                errors.add(error);
                continue;
            }

            data.add(serPlan);

            for (DWSerPlanItem serPlanItem : serPlan.getSerPlanItems()) {
                ErrorInfoElement subError = serPlanItem.valid(serPlan.getSerPlanId());
                if (subError!=null) {
                    errors.add(error);
                    continue;
                }

                subData.add(serPlanItem);
            }
        }

        if (!errors.isEmpty()) {
            respContent = XMLBuilder.simpleResp("0", "Failure", errors);
        } else {
            try {
                if (!data.isEmpty()) {
                    this.dao.insertOrUpdate(data);
                }
                if (!subData.isEmpty()) {
                    this.dao.insertOrUpdate(subData);
                }
            } catch (Exception e) {
                logger.error("Insert DW server plan and plan item data fail!!!", e);
            }
        }

        return respContent;
    }

    public String syncUpdate(List<DWServicePlan> servicePlans) {
        String respContent = this.respCnt;

        return respContent;
    }
}
